package com.example.camerademoexcercies1;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.Face;
import android.hardware.camera2.params.MeteringRectangle;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.AudioManager;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaActionSound;
import android.media.MediaParser;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Size;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.TextureView;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.core.app.ActivityCompat;
import androidx.viewpager.widget.ViewPager;

import com.example.camerademoexcercies1.activity.AlbumActivity;
import com.example.camerademoexcercies1.fragment.MyMenuFragmentAdapter;
import com.example.camerademoexcercies1.tool.BitmapTool;
import com.example.camerademoexcercies1.tool.GetBitmap;
import com.example.camerademoexcercies1.tool.LogTool;
import com.example.camerademoexcercies1.view.Anticlockwise;
import com.example.camerademoexcercies1.view.CountDownView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SimplifyCamera<timer> extends AppCompatActivity implements
        View.OnClickListener,
        View.OnTouchListener,TextWatcher {

    /*
      现在的问题是什么?
      双指缩放
     */

    /**
     * 0.聚焦动画
     * 1.动态调节分辨率
     * 2.切换录像
     * 3.相册 附带删除
     * 4.动态设置曝光，白平衡参数
     * 5.以MVP方式重构代码
     */


    /*设置全局参数*/
    private long firstTime = 0;
    private int textureWidth;
    private int textureHeight;
    private float mZoomValue;
    private float oldDist;
    private boolean isRecording;
    private String rootPath;
    private String cameraId;
    private String touchMode = "Single";
    private ImageButton takePhotoButton;
    private ImageButton rotateButton;
    private ImageButton btn_flash;
    private TextureView texturePreview;
    private TextView zoomNumber;
    private ImageReader imageReader;
    private ImageView albumImage;
    private Image captureImage;
    private CameraManager cameraManager;
    private CameraCharacteristics cameraCharacteristics;
    private CameraDevice cameraDevice;
    private HandlerThread handlerThread;
    private Handler mBackgroundHandler;
    private CaptureRequest.Builder previewBuilder;
    private CaptureRequest.Builder captureBuilder;
    private CameraCaptureSession previewSession;
    private Integer menuVisible = 0;
    private ImageButton menuButton;
    private ViewPager viewPager;
    private LinearLayout parentLayout;
    private ConstraintLayout bottomConstraint;
    private SurfaceHolder holder;
    private SurfaceTexture surfaceTexture;
    private Surface previewSurface;
    private Surface mediaRecorderSurface;
    private MyOrientationListener myOrientationListener;
    private final SeekBar.OnSeekBarChangeListener seekListener;
    private final View.OnClickListener tagListener;
    private final View.OnClickListener flashListener;
    private final ImageReader.OnImageAvailableListener imageReaderListener;
    private CameraCaptureSession.CaptureCallback previewCallBack;
    private File videoFile;
    private String cameraMode;
    private Size optimalSize;
    private MediaRecorder recorder;


    private ImageView image_focus;
    private SeekBar zoomSeekBar;
    private List<TextView> tagViews;
    private Long nowTimer = 0L;
    private Long oldTimer = 0L;

    //    创建seekBar的监听
    {
        seekListener = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mZoomValue = (float) (progress * 0.01);
                applyZoom(mZoomValue);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        };
    }

    // 给tags的点击监听
    {
        tagListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (((TextView) v).getCurrentTextColor() !=
                        SimplifyCamera.this.getResources().getColor(R.color.blue)) {
                    for (TextView view : tagViews) {
                        if (view.getId() != v.getId()) {
                            view.setTextColor(SimplifyCamera.this.getResources().getColor(R.color.white));
                        } else {
                            view.setTextColor(SimplifyCamera.this.getResources().getColor(R.color.blue));
                        }
                    }
                    if (v.getId() == tagViews.get(0).getId()) {
                        takePhotoButton.setId(R.id.btn_simple_delayed);
                        takePhotoButton.setOnClickListener(SimplifyCamera.this);
                        takePhotoButton.setImageResource(R.drawable.btn_camera_all);
                    } else if (v.getId() == tagViews.get(1).getId()) {
                        takePhotoButton.setId(R.id.btn_simple_takePhoto);
                        takePhotoButton.setOnClickListener(SimplifyCamera.this);
                        takePhotoButton.setImageResource(R.drawable.icon_recorder_white);
                    } else if (v.getId() == tagViews.get(2).getId()) {
                        takePhotoButton.setId(R.id.btn_simple_record);
                        takePhotoButton.setOnClickListener(SimplifyCamera.this);
                        takePhotoButton.setImageResource(R.drawable.icon_recorder_red);
                    }

                } else say("按兵不动");
            }
        };
    }

    //  闪光灯监听
    {
        flashListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (previewBuilder.get(CaptureRequest.FLASH_MODE).equals(CaptureRequest.FLASH_MODE_OFF)) {
                    previewBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
                    previewBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_TORCH);

                    try {
                        previewSession.setRepeatingRequest(previewBuilder.build(), previewCallBack, mBackgroundHandler);
                        btn_flash.setBackground(SimplifyCamera.this.getResources().getDrawable(R.drawable.icon_shangguangdengoff));
                        say("闪光灯开启");
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                } else {
                    previewBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
                    try {
                        previewSession.setRepeatingRequest(previewBuilder.build(), previewCallBack, mBackgroundHandler);
                        btn_flash.setBackground(SimplifyCamera.this.getResources().getDrawable(R.drawable.icon_shanguangdeng));
                        say("闪光灯关闭");
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
    }

    //  创建预览回调
    {
        previewCallBack = new CameraCaptureSession.CaptureCallback() {
            @Override
            public void onCaptureStarted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, long timestamp, long frameNumber) {
                super.onCaptureStarted(session, request, timestamp, frameNumber);


            }

            @Override
            public void onCaptureProgressed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureResult partialResult) {
                super.onCaptureProgressed(session, request, partialResult);
            }

            @Override
            public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
                super.onCaptureCompleted(session, request, result);
                SimplifyCamera.this.onCameraImagePreviewed(result);
            }
        };
    }


    //人脸数检测
    private void faces(CaptureResult result){
        Face faces[] = result.get(CaptureResult.STATISTICS_FACES);
        Toast.makeText(SimplifyCamera.this, "检测到有人脸数"+faces.length, Toast.LENGTH_LONG).show();
    }


    //  创建imageReader监听
    {
        //  拍照回传数据
        imageReaderListener = new ImageReader.OnImageAvailableListener() {
            @Override
            public void onImageAvailable(final ImageReader reader) {
                    say("进入onImageVailable");
                    new Runnable(){
                        @Override
                        public void run() {
                            captureImage = reader.acquireNextImage();
                            ByteBuffer buffer = captureImage.getPlanes()[0].getBuffer();
                            byte[] data = new byte[buffer.remaining()];
                            buffer.get(data);
                            captureImage.close();
                            Bitmap bitmap = BitmapTool.rotateBitmapByDegree(
                                    BitmapFactory.decodeByteArray(data, 0, data.length),
                                    (cameraId.equals("0") ? 90 : 270));
                            try {
                                File finalPath = new File(rootPath, System.currentTimeMillis() + ".jpg");
                                FileOutputStream fos = new FileOutputStream(finalPath);
                                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                                fos.flush();
                                fos.close();
                                say("图片已保存");
                                notifyUpdate(new File(String.valueOf(finalPath)));
                                say("通知图库完成");
                                new GetLatestAlbum().run();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }.run();

            }
        };
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        parentLayout = (LinearLayout) inflater.inflate(R.layout.activity_simplify_camera, null);
        setContentView(parentLayout);
        myOrientationListener = new MyOrientationListener(this);
        boolean autoRotateOn = (Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1);
        //检查系统是否开启自动旋转
        if (autoRotateOn) {
            myOrientationListener.enable();
        }
        initEvent();
        startBackgroundThread();
        initCameraManager("0");
        initTextureView();

        cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

        //timers();
        editText = (EditText) findViewById(R.id.tx_time);
        editText.addTextChangedListener(this);
        mTvCountDown = (TextView) findViewById(R.id.count_down);

        //人脸识别
        faceView = findViewById(R.id.face_view);
        faceView.setAlpha(0.9f);

    }







    //倒计时
   /* private CountDownView countDownView;
    private void timers(){
        countDownView = findViewById(R.id.countDownView);
        countDownView.setOnCountDownListener(new CountDownView.OnCountDownListener() {
            @Override
            public void countDownFinished() {


                Toast.makeText(SimplifyCamera.this, "倒计时结束", Toast.LENGTH_SHORT).show();
            }
        });




        *//*int times = 0;
        EditText editText = (EditText) findViewById(R.id.tx_time);
        String time = editText.getText().toString();
        if(time.equals("") || time == null){
            return;
        }else {
             times= Integer.parseInt(time);
        }
        Log.e("TAG","time__________"+time);*//*

        countDownView.setCountdownTime(50);
        countDownView.startCountDown();

        countDownView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                countDownView.stopCountDdwn();
            }
        });
    }*/

    //    点击事件
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_simple_takePhoto) { // 拍照
            Log.e("TAG","拍照声音+++++++++++++++++");
            oldTimer = 0L;
            say("点击拍照完成");
            takePhotoButton.setClickable(false);
            takePhoto();
            shutter();
        } else if (v.getId() == R.id.btn_simple_record) {
            say("点击了录像");
            takePhotoButton.setClickable(false);
            takeVideo();
        }else if (v.getId() == R.id.btn_simple_delayed) {
            say("点击了延时拍照");
            if(!mIsTimerRunning){
                oldTimer = 0L;
                takePhotoButton.setClickable(false);
                mIsTimerRunning = true;
                mHandler.post(timerRunnable);
                say("点击延时拍照完成");
            }
        } else if (v.getId() == R.id.btn_simple_rotate) { // 旋转摄像头
            Log.e("TAG","用户点击了切换摄像头按钮");
            rotateCamera();
        } else if (v.getId() == R.id.btn_simple_album) { // 跳转最新图片
            Intent intent = new Intent(this, AlbumActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else if (v.getId() == R.id.btn_options) { // 菜单栏打开收起动画
            //  定义两个菜单栏弹出和收回动画
            final TranslateAnimation animationFromUpToDown = new TranslateAnimation(
                    TranslateAnimation.RELATIVE_TO_SELF, 0, TranslateAnimation.RELATIVE_TO_SELF, 0,
                    TranslateAnimation.RELATIVE_TO_SELF, -1, TranslateAnimation.RELATIVE_TO_SELF, 0);
            final TranslateAnimation animationFromDownToUp = new TranslateAnimation(
                    TranslateAnimation.RELATIVE_TO_SELF, 0, TranslateAnimation.RELATIVE_TO_SELF, 0,
                    TranslateAnimation.RELATIVE_TO_SELF, 0, TranslateAnimation.RELATIVE_TO_SELF, -1);
            animationFromDownToUp.setDuration(450);
            animationFromUpToDown.setDuration(450);
            if (menuVisible == 0) {
                viewPager.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        viewPager.setVisibility(menuVisible);
                        viewPager.startAnimation(animationFromUpToDown);
                        menuVisible = 4;
                    }
                }, 0);
            } else {
                viewPager.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        viewPager.setVisibility(menuVisible);
                        viewPager.setAnimation(animationFromDownToUp);
                        menuVisible = 0;
                    }
                }, 0);
            }
        } else if (v.getId() == R.id.btn_zoom) { // 打开缩放滑动条
            if (zoomSeekBar.getVisibility() == View.INVISIBLE) {
                zoomSeekBar.setVisibility(View.VISIBLE);
            } else if (zoomSeekBar.getVisibility() == View.VISIBLE) {
                zoomSeekBar.setVisibility(View.INVISIBLE);
            }
        }
    }


    //拍照声音
    private MediaPlayer mediaPlayer;
    private AudioManager audioManager;
    private void shutter(){
        audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        mediaPlayer = MediaPlayer.create(this,R.raw.shut);
        //mediaPlayer.setLooping(true); //循环播放声音
        mediaPlayer.start();
    }

    //录像声音
    private void video(){
        audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        mediaPlayer = MediaPlayer.create(this,R.raw.recoder);
        mediaPlayer.start();
    }

    //    触摸事件
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (v.getId() == R.id.simple_texture_preview) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (touchMode.equals("Double")) {
                    touchMode = "Single";
                } else {
                    zoomSeekBar.setVisibility(View.INVISIBLE);
                    zoomNumber.setVisibility(View.INVISIBLE);
                    Point point = new Point((int) event.getX(), (int) event.getY());
                    new Focus(point).run();
                    startControlAFRequest(calcTapAreaForCamera2(cameraCharacteristics, point.x, point.y, 10, 2));
                }
            } else if (event.getAction() == 261) {
                touchMode = "Double";
                oldDist = distance(event);
                zoomSeekBar.setVisibility(View.VISIBLE);
                zoomNumber.setVisibility(View.VISIBLE);
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                if (touchMode.equals("Double")) {
                    // 两个手指滑动
                    float newDist = distance(event);
                    if (mZoomValue <= 1.0F){
                        mZoomValue = Math.max((float) (mZoomValue + (newDist - oldDist) * 0.00005),0);
                    } else mZoomValue = 1.0F;

                    zoomSeekBar.setProgress((int) (mZoomValue * 100));
                    say("mZoomValue = " + mZoomValue);
                    applyZoom(mZoomValue);
                }
            }
        }
        return true;
    }

    //    旋转摄像头
    private void rotateCamera() {
        rotateButton.setClickable(false);
        previewSession.close();
        previewSession = null;

        if(cameraDevice != null){
            cameraDevice.close();
            cameraDevice = null;
        }
        if (cameraId.equals("0")) {
            initCameraManager("1");

        } else initCameraManager("0");
        mBackgroundHandler.post(new OpenCameraThread());
    }

    /*private int mCameraID;
    private void rotateCamera() {
        if (cameraDevice != null) {
            cameraDevice.close();
            cameraDevice = null;
        }

        if(cameraId.equals("") || cameraId == null){
            mCameraID = Integer.parseInt(cameraId);
        }
        mCameraID ^= 1;
        Log.e("TAG","mCameraID______________"+mCameraID);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            return;
        }
        try {
            initCameraManager(String.valueOf(mCameraID));
            cameraManager.openCamera(String.valueOf(mCameraID) + "",mCameraDeviceStateCallback, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }*/

    //    初始化画布，就绪后打开摄像头
    private void initTextureView() {
        texturePreview.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
                optimalSize = getOptimalSize(textureWidth, textureHeight);
                textureWidth = width;
                textureHeight = height;
                surfaceTexture = surface;
                surfaceTexture.setDefaultBufferSize(optimalSize.getWidth(), optimalSize.getHeight());
                previewSurface = new Surface(surfaceTexture);
                //  初始化imageReader
                imageReader = ImageReader.newInstance(optimalSize.getWidth(), optimalSize.getHeight(), ImageFormat.JPEG, 2);
                imageReader.setOnImageAvailableListener(imageReaderListener,mBackgroundHandler);
                say("添加texture监听，可用回调计算得到最佳尺寸：" + optimalSize.getWidth() + "*" + optimalSize.getHeight() + "  初始化preview和imageReader");
                mBackgroundHandler.post(new OpenCameraThread());
            }

            @Override
            public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {
                say("onSurfaceTextureSizeChanged");
            }

            @Override
            public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
                say("onSurfaceTextureDestroyed");
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {
            }
        });
    }

    //    初始化cameraManager和cameraCharacteristics还有CameraId（manager开摄像头用）
    private void initCameraManager(String id) {
        cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        cameraId = id;
        say("初始化cameraManager&相机ID为：" + cameraId);
        try {
            /*有可能该摄像头不存在*/
            cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId);
            float zoom = cameraCharacteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM);
            say("初始化对应相机ID的cameraCharacteristics\t支持变焦倍数:" + zoom);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }

       /* try {
            cameraIdList = cameraManager.getCameraIdList();
            if(cameraIdList == null || cameraIdList.length == 0){
                Toast.makeText(this,"当前没有摄像头",Toast.LENGTH_SHORT).show();
            }else{
                for (int i=0;i<cameraIdList.length;i++){
                    Log.e("TAG","index:"+i+",cameraId"+cameraIdList[i]);
                }
                cameraId = cameraIdList[CameraCharacteristics.LENS_FACING_FRONT];
                cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId);
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }*/
    }




    //    初始化事件 绑定组件什么的
    @SuppressLint("ClickableViewAccessibility")
    private void initEvent() {
        tagViews = new ArrayList<>();
        MyMenuFragmentAdapter adapter = new MyMenuFragmentAdapter(getSupportFragmentManager());
        viewPager = parentLayout.findViewById(R.id.viewPaper_layout);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0);
        viewPager.setAlpha(0.8F);

        takePhotoButton = parentLayout.findViewById(R.id.btn_simple_takePhoto);
        rotateButton = parentLayout.findViewById(R.id.btn_simple_rotate);
        albumImage = parentLayout.findViewById(R.id.btn_simple_album);
        menuButton = parentLayout.findViewById(R.id.btn_options);
        image_focus = parentLayout.findViewById(R.id.image_focus);
        texturePreview = parentLayout.findViewById(R.id.simple_texture_preview);
        bottomConstraint = parentLayout.findViewById(R.id.simple_bottom_constraintLayout);
        zoomNumber = parentLayout.findViewById(R.id.text_zoom_number);
        tagViews.add((TextView) parentLayout.findViewById(R.id.choice_takeBurst));
        tagViews.add((TextView) parentLayout.findViewById(R.id.choice_takePhoto));
        tagViews.add((TextView) parentLayout.findViewById(R.id.choice_takeVideo));
        for (final TextView tagView : tagViews) {
            tagView.setOnClickListener(tagListener);
        }
        btn_flash = parentLayout.findViewById(R.id.btn_flash);
        btn_flash.setOnClickListener(flashListener);
        parentLayout.findViewById(R.id.btn_zoom).setOnClickListener(this);
        zoomSeekBar = (SeekBar) parentLayout.findViewById(R.id.zoom_seekBar);
        zoomSeekBar.setOnSeekBarChangeListener(seekListener);
        texturePreview.setOnTouchListener(this);
        menuButton.setOnClickListener(this);
        takePhotoButton.setOnClickListener(this);
        rotateButton.setOnClickListener(this);
        albumImage.setOnClickListener(this);
        rootPath = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM)), "CameraTestStorage").toString() + "/";
        new GetLatestAlbum().run();
        mZoomValue = 0f;
        isRecording = false;
        say("事件绑定完成，相册目录初始化完成：" + rootPath);
    }

    //    计算两个触摸点之间的距离
    private float distance(MotionEvent event) {
        float x = 0;
        float y = 0;
        try {
            x = event.getX(0) - event.getX(1);
            y = event.getY(0) - event.getY(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (float) Math.sqrt(x * x + y * y);
    }

    //    触摸点换算成底层坐标
    private MeteringRectangle calcTapAreaForCamera2(CameraCharacteristics c,
                                                    int currentX,
                                                    int currentY,
                                                    int areaSize,
                                                    int weight) {
        // 获取Size
        Rect rect = c.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
        Rect newRect;
        int leftPos, topPos;
        // 坐标转换
        float newX = currentY;
        float newY = textureWidth - currentX;
        // 大小转换
        leftPos = (int) ((newX / textureHeight) * rect.right);
        topPos = (int) ((newY / textureHeight) * rect.bottom);
        // 以坐标点为中心生成一个矩形, 需要防止上下左右的值溢出
        int left = clamp(leftPos - areaSize, 0, rect.right);
        int top = clamp(topPos - areaSize, 0, rect.bottom);
        int right = clamp(leftPos + areaSize, leftPos, rect.right);
        int bottom = clamp(topPos + areaSize, topPos, rect.bottom);
        newRect = new Rect(left, top, right, bottom);
        say(newRect.toString());
        // 构造MeteringRectangle
        return new MeteringRectangle(newRect, weight);
    }

    //    触摸边界计算
    private int clamp(int x, int min, int max) {
        if (x > max) {
            return max;
        }
        if (x < min) {
            return min;
        }
        return x;
    }

    //    触发手动对焦
    public void startControlAFRequest(MeteringRectangle rect) {

        MeteringRectangle[] rectangle = new MeteringRectangle[]{rect};
        // 对焦模式必须设置为AUTO
        previewBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_AUTO);
        //AE
        previewBuilder.set(CaptureRequest.CONTROL_AE_REGIONS, rectangle);
        //AF 此处AF和AE用的同一个rect, 实际AE矩形面积比AF稍大, 这样测光效果更好
        previewBuilder.set(CaptureRequest.CONTROL_AF_REGIONS, rectangle);
        try {
            // AE/AF区域设置通过setRepeatingRequest不断发请求
            previewSession.setRepeatingRequest(previewBuilder.build(), null, mBackgroundHandler);
            //触发对焦
            previewBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_START);
            //触发对焦通过capture发送请求, 因为用户点击屏幕后只需触发一次对焦
            previewSession.capture(previewBuilder.build(), null, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    //    修改缩放参数
    public void applyZoom(float zoom) {
        mZoomValue = zoom;
        if (cameraCharacteristics != null) {
            float maxZoom = cameraCharacteristics.get(
                    CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM);
            float realZoom =(float) Math.round(((mZoomValue * (maxZoom - 1.0f)) + 1.0f) * 10) / 10;
            zoomNumber.setText(String.valueOf(realZoom));
            Rect newRect = getZoomRect(realZoom, maxZoom);
            previewBuilder.set(CaptureRequest.SCALER_CROP_REGION, newRect);
            previewBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
            try {
                previewSession.setRepeatingRequest(previewBuilder.build(), null, mBackgroundHandler);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }
    }

    //    获取缩放截取范围
    private Rect getZoomRect(float zoomLevel, float maxDigitalZoom) {
        Rect activeRect = new Rect();

        activeRect = cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);

        int minW = (int) (activeRect.width() / maxDigitalZoom);
        int minH = (int) (activeRect.height() / maxDigitalZoom);
        int difW = activeRect.width() - minW;
        int difH = activeRect.height() - minH;

        // When zoom is 1, we want to return new Rect(0, 0, width, height).
        // When zoom is maxZoom, we want to return a centered rect with minW and minH
        int cropW = (int) (difW * (zoomLevel - 1) / (maxDigitalZoom - 1) / 2F);
        int cropH = (int) (difH * (zoomLevel - 1) / (maxDigitalZoom - 1) / 2F);
        return new Rect(cropW, cropH, activeRect.width() - cropW,
                activeRect.height() - cropH);
    }

    //    让所有的回调跑在这个非主线程上
    private void startBackgroundThread() {
        handlerThread = new HandlerThread("CameraThread");
        handlerThread.start();
        mBackgroundHandler = new Handler(handlerThread.getLooper());
        say("开启后台线程");
    }

    private CameraDevice.StateCallback mCameraDeviceStateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(@NonNull CameraDevice camera) {
            cameraDevice = camera;
            say("开启" + (cameraId.equals("0") ? "后置摄像头" : "前置摄像头") + ",初始化Device，开始会话创建线程");
            new CreatePreviewSessionThread().run();
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice camera) {

        }

        @Override
        public void onError(@NonNull CameraDevice camera, int error) {

        }
    };

    //    相机开启线程
    public class OpenCameraThread implements Runnable {

        @Override
        public void run() {
            openCamera();
        }

        //    相机开启
        @SuppressLint("MissingPermission")
        private void openCamera() {
            try {
                cameraManager.openCamera(cameraId,mCameraDeviceStateCallback, mBackgroundHandler);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }
    }

    //    创建预览会话线程
    public class CreatePreviewSessionThread implements Runnable {

        @Override
        public void run() {
            if (previewBuilder == null) {
                initPreview();
                say("初始化完对应预览builder和参数");
            }
            if (previewSession != null) {
                clearPreviewSession();
            }
            createPreviewSession();
        }

        //    创建预览会话
        private void createPreviewSession() {
            try {
                // 创建循环请求
                if (cameraDevice != null) {
                    cameraDevice.createCaptureSession(Arrays.asList(previewSurface, imageReader.getSurface()), new CameraCaptureSession.StateCallback() {
                        @Override
                        public void onConfigured(@NonNull CameraCaptureSession session) {
                            previewSession = session;
                            try {
                                previewSession.setRepeatingRequest(previewBuilder.build(), previewCallBack, mBackgroundHandler);
                                rotateButton.setClickable(true);
                                say("预览开启成功");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onConfigureFailed(@NonNull CameraCaptureSession session) {

                        }
                    }, mBackgroundHandler);
                } else say("cameraDevice 为空,无法创建captureSession");

            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }


        public void initPreview() {
            try {
                previewBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
            previewBuilder.addTarget(previewSurface);
            // 自动对焦
            previewBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
            // 闪光灯
            previewBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
            // 根据摄像头方向对保存的照片进行旋转，使其为"自然方向"
            Integer mCameraSensorOrientation = cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
            previewBuilder.set(CaptureRequest.JPEG_ORIENTATION, mCameraSensorOrientation);
            // 人脸检测模式
            previewBuilder.set(CaptureRequest.STATISTICS_FACE_DETECT_MODE, CameraCharacteristics.STATISTICS_FACE_DETECT_MODE_SIMPLE);
            //获取成像区域
            Rect cRect = cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
            //支持的最大检测人脸数量
            cPixelSize = cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE);

            //可用于判断是否支持人脸检测，以及支持到哪种程度
            faceDetectModes = cameraCharacteristics.get(CameraCharacteristics.STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES);//支持的人脸检测模式
            int maxFaceCount = cameraCharacteristics.get(CameraCharacteristics.STATISTICS_INFO_MAX_FACE_COUNT);//支持的最大检测人脸数量

            previewBuilder.set(CaptureRequest.STATISTICS_FACE_DETECT_MODE,getFaceDetectMode());
        }
    }

    //    创建拍照会话线程
    public class CreateCaptureSessionThread implements Runnable {

        @Override
        public void run() {
            if (captureBuilder == null) {
                initCapture();
            }
            createCaptureSession();
        }

        //    预览转拍照
        private void createCaptureSession() {
            try {
                //  停止预览开始拍照
                previewSession.stopRepeating();
                previewSession.abortCaptures();
                say("预览停止");
                previewSession.capture(captureBuilder.build(), new CameraCaptureSession.CaptureCallback() {
                    @Override
                    public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
                        super.onCaptureCompleted(session, request, result);
                        try {
                            previewSession.setRepeatingRequest(previewBuilder.build(), previewCallBack, mBackgroundHandler);
                            takePhotoButton.setClickable(true);

                            //检测人脸数
                            faces(result);

                            say("重启结束");
                        } catch (CameraAccessException e) {
                            e.printStackTrace();
                        }
                        SimplifyCamera.this.onCameraImagePreviewed(result);
                    }
                }, mBackgroundHandler);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }

        }

        //    初始化拍摄参数
        public void initCapture() {
            try {
                captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
            // 自动对焦
            captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
            // 闪光灯
            captureBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
            // 根据摄像头方向对保存的照片进行旋转，使其为"自然方向"

            captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, 90);
            // 人脸检测模式
            captureBuilder.set(CaptureRequest.STATISTICS_FACE_DETECT_MODE, CameraCharacteristics.STATISTICS_FACE_DETECT_MODE_SIMPLE);

            captureBuilder.addTarget(previewSurface);
            captureBuilder.addTarget(imageReader.getSurface());
            say("初始化完成拍照参数");
        }
    }

    //    开个线程来加载最新图片
    public class GetLatestAlbum implements Runnable {

        @Override
        public void run() {
            getLatestAlbum();
        }
        //    获取本软件自定义目录下最新的照片
        private void getLatestAlbum() {
            File albumDirectory = new File(rootPath);
            if (albumDirectory.isDirectory() || albumDirectory.mkdir()) {
                List<String> fileList = new ArrayList<>();
                for (File file : Objects.requireNonNull(albumDirectory.listFiles())) {
                    fileList.add(file.toString());
                }
                int maxID = 0;
                long maxLong = 0L;
                String reg = "(?<=" + rootPath + ")\\d{13}(?=\\.jpg)";
                Pattern r = Pattern.compile(reg);
                for (int i = 0; i < fileList.size(); i++) {
                    Matcher matcher = r.matcher(fileList.get(i));
                    while (matcher.find()) {
                        if (Long.parseLong(matcher.group()) > maxLong) {
                            maxID = i;
                            maxLong = Long.parseLong(matcher.group());
                        }
                    }
                }
                //  文件夹内可能无文件导致读取第一张报错
                if (fileList.size() != 0) {
                    String showImage = fileList.get(maxID);
                    final Bitmap bitmap = GetBitmap.getBitmap(showImage);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            albumImage.setImageBitmap(BitmapTool.bitmapToCircle(Objects.requireNonNull(BitmapTool.bitmapToSquare(bitmap,
                                    bitmap.getWidth() - 1)), 2));
                        }
                    });
                }
            } else {
                say("图片读取，路径无法创建");
                Toast.makeText(SimplifyCamera.this, "图片读取，路径无法创建", Toast.LENGTH_LONG).show();
            }
        }
    }

    //    聚焦线程
    public class Focus implements Runnable {

        private Point point;
        private ConstraintSet applyConstrainSet = new ConstraintSet();
        private ConstraintLayout constraintLayout = findViewById(R.id.constraint_preview);
        private Animation animation;

        public Focus(Point point) {
            this.point = point;
        }

        @Override
        public void run() {
            animation = AnimationUtils.loadAnimation(SimplifyCamera.this, R.anim.anim_scale);
            image_focus.startAnimation(animation);
            image_focus.setVisibility(View.VISIBLE);
            applyConstrainSet.clone(constraintLayout);
            applyConstrainSet.setMargin(image_focus.getId(), ConstraintSet.LEFT, point.x - (image_focus.getWidth() / 2));
            applyConstrainSet.setMargin(image_focus.getId(), ConstraintSet.TOP, point.y - (image_focus.getHeight() / 2));
            applyConstrainSet.applyTo(constraintLayout);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    image_focus.setVisibility(View.GONE);
                }
            }, 1000);
        }
    }

    //    获取当前Characteristic分辨率最高的Size
    public Size getOptimalSize(int textureWidth, int textureHeight) {
        StreamConfigurationMap configurationMap = //一份详细的配置表
                cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        Size[] sizeList = configurationMap.getOutputSizes(SurfaceTexture.class); //提供一个可输出Size的类
        List<Size> readyList = new ArrayList<>();
//            先找尺寸接近的，再找其中分辨率最高的
        float bestRatio = (float) textureHeight / textureWidth;
        int maxSize = 0;
        for (Size size : sizeList) {
            if (Math.abs(((float) size.getWidth() / size.getHeight() - bestRatio)) < 0.3) {
                readyList.add(size);
            }
        }
        for (Size size : readyList) {
            if (size.getWidth() > maxSize) {
                maxSize = size.getWidth();
                sizeList[0] = size;
            }
        }
        return sizeList[0];

    }

    //    直接拿textureView里的bitmap存起来，算是拍照吧
    private void takePhoto() {
        new CreateCaptureSessionThread().run();
    }

    //    录像
    private void takeVideo() {
        //            开始录制转停止录制
        if (isRecording) {
            recorder.stop();
            recorder.release();
            recorder = null;
            isRecording = false;
            previewBuilder.removeTarget(mediaRecorderSurface);
            //  将preview和mediaSurface作为target开始预览
            new CreatePreviewSessionThread().run();
            bottomConstraint.setAlpha(1);
            say("————stop recording————");
            video();
        } else {
            //  暂停预览，准备media，初始化，camera再开启一个预览会话
            initMediaRecorder();
            recorder.start();
            isRecording = true;
            bottomConstraint.setAlpha(0.2F);
            say("————start recording————");
            video();
        }
        takePhotoButton.setClickable(true);
    }

    //    初始化mediaRecorder
    public void initMediaRecorder() {
        File videoRootPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                "MediaRecorderStorage");
        if (!videoRootPath.exists() && !videoRootPath.mkdir()) {
            say("根目录:videoRootPath(" + videoRootPath.toString() + ")创建失败");
        } else {
            videoFile = new File(videoRootPath, "video" + System.currentTimeMillis() + ".mp4");
            say("输出文件(" + videoFile);
        }
        clearPreviewSession();
        recorder = new MediaRecorder();
        say("新建recorder");
        //    这两项需要放在setOutputFormat之前
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        say("看看尺寸差别： width :" + textureWidth + " height :" + textureHeight + " optimal :" + optimalSize.toString());
        recorder.setVideoSize(optimalSize.getWidth(), optimalSize.getHeight());
        recorder.setVideoEncodingBitRate(10000000);
        recorder.setVideoFrameRate(30);
        if (cameraId.equals("0")) {
            recorder.setOrientationHint(90);
        } else {
            recorder.setOrientationHint(270);
        }
        recorder.setPreviewDisplay(previewSurface);
        recorder.setMaxDuration(30 * 1000);
        recorder.setOutputFile(videoFile.getAbsolutePath());
        say("参数设置完成");
        try {
            recorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        say("recorder就绪");
        mediaRecorderSurface = recorder.getSurface();
        say("获取到mediaSurface");

        try {
            previewBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_VIDEO);
            previewBuilder.addTarget(previewSurface);
            previewBuilder.addTarget(mediaRecorderSurface);
            cameraDevice.createCaptureSession(Arrays.asList(previewSurface, mediaRecorderSurface), new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(@NonNull CameraCaptureSession session) {
                    previewSession = session;
                    try {
                        previewSession.setRepeatingRequest(previewBuilder.build(), null, mBackgroundHandler);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession session) {

                }
            }, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        say("录像模式预览完成");
    }

    //    通知图库更新
    private void notifyUpdate(File file) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { //要求sdk大于25 android7.0及以上 储存方式发生了改变
            MediaScannerConnection.scanFile(this, new String[]{file.getAbsolutePath()}, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        @Override
                        public void onScanCompleted(String path, Uri uri) {
                            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                            mediaScanIntent.setData(uri);
                            sendBroadcast(mediaScanIntent); //扫描完毕，发送广播通知图库更新
                            new GetLatestAlbum().run();
                        }
                    });
        } else {
            say("设备的版本低于Android7.0");
            String relationDir = file.getParent();
            assert relationDir != null;
            File file1 = new File(relationDir);
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile(file1.getAbsoluteFile())));
        }
    }

    //    关闭并清空session
    private void clearPreviewSession() {
        try {
            previewSession.stopRepeating();
            previewSession.close();
            previewSession = null;
            say("清空previewSession");
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    //    打印
    public void say(String word) {
        if (oldTimer == 0L) {
            oldTimer = System.currentTimeMillis();
            LogTool.log("开始计时\t" + word);
        } else {
            nowTimer = System.currentTimeMillis();
            long dist = nowTimer - oldTimer;
            if (dist < 5000L) {
                LogTool.log(("耗时：" + (dist) + "\t\t") + word);
                oldTimer = nowTimer;
            } else {
                LogTool.log("超时：" + (dist) + "\t\t" + word);
                oldTimer = 0L;
            }
        }
    }

    //    返回退出功能
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                Toast.makeText(this, "再按一次退出程序", (int) 2000).show();
                firstTime = secondTime;
                return true;
            } else {
                finish();
                System.exit(0);
            }
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onPause() {
        say("-------------SimplifyActivity paused-------------");
        super.onPause();
    }

    @Override
    protected void onResume() {
        say("-------------SimplifyActivity Resumed-------------");
        if (previewBuilder != null) {
            mBackgroundHandler.post(new OpenCameraThread());
        }
        super.onResume();
    }

    @Override
    protected void onStop() {
        say("-------------SimplifyActivity stopped-------------");
        if (previewSession != null) {
            say("previewSession不为空，关闭其清空对应session和device，重新启动openCamera线程");
            previewSession.close();
            previewSession = null;
            cameraDevice.close();
            cameraDevice = null;
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        say("-------------SimplifyActivity destroyed-------------");
        super.onDestroy();
        myOrientationListener.disable();
    }

    class MyOrientationListener extends OrientationEventListener {
        public MyOrientationListener(Context context) {
            super(context);
        }

        public MyOrientationListener(Context context, int rate) {
            super(context, rate);
        }

        @Override
        public void onOrientationChanged(int orientation) {
            int screenOrientation = getResources().getConfiguration().orientation;

            if (((orientation >= 0) && (orientation < 45)) || (orientation > 315)) {    //设置竖屏
                if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT && orientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
                    say("设置竖屏");
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
            } else if (orientation > 225 && orientation < 315) { //设置横屏
                say("设置横屏");
                if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
            } else if (orientation > 45 && orientation < 135) {// 设置反向横屏
                say("设置反向横屏");
                if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
                }
            } else if (orientation > 135 && orientation < 225) { //反向竖屏
                say("设置反向竖屏");
                if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
                }
            }
        }
    }

    //延时拍照
    private TextView mTvCountDown;
    private boolean mIsTimerRunning = false;
    private Handler mHandler = new Handler();
    private int times=0;
    private int mCurrentTimer = 5;

    private Runnable timerRunnable = new Runnable() {
        @Override
        public void run() {
            if(mCurrentTimer > 0){
                mTvCountDown.setText(mCurrentTimer + "");

                mCurrentTimer--;
                mHandler.postDelayed(timerRunnable,1000);

            }else{
                mTvCountDown.setText("");
                takePhoto();
                shutter();
                mIsTimerRunning = false;
                mCurrentTimer = 5;
            }
        }
    };

    //监听文本框的值
    private EditText editText;
    private CharSequence time;//监听前的文本
    private boolean DEBUG = true;
    private String str;
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        EditText editText = (EditText) findViewById(R.id.tx_time);
        time = editText.getText().toString();
        Log.e("TAG","time__________"+time);
        if(time.equals("") || time == null){
            return;
        }else {
            str= time.toString();
        }
        if(str.equals("") || str == null){
            return;
        }else{
            times = Integer.valueOf(str).intValue();
        }
        Log.e("TAG","times+++++++++++"+times);
    }

    private Size cPixelSize;
    private int[] faceDetectModes;
    private TextureView faceView;
    //处理相机画面处理完成事件，获取检测到的人脸坐标，换算并绘制人脸方框
    private void onCameraImagePreviewed(CaptureResult result){
        Face faces[]=result.get(CaptureResult.STATISTICS_FACES);

        //Log.e("TAG","Face" + faces.length);
        Canvas canvas = faceView.lockCanvas();
        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);//旧画面清理覆盖

        if(faces.length>0){
            for(int i=0;i<faces.length;i++){
                Rect fRect = faces[i].getBounds();

                //人脸检测坐标基于相机成像画面尺寸以及坐标原点。此处进行比例换算
                //成像画面与方框绘制画布长宽比比例（同画面角度情况下的长宽比例（此处前后摄像头成像画面相对预览画面倒置（±90°），计算比例时长宽互换））
                float scaleWidth = canvas.getHeight()*1.0f/cPixelSize.getWidth();
                float scaleHeight = canvas.getWidth()*1.0f/cPixelSize.getHeight();

                //坐标缩放
                int l = (int) (fRect.left*scaleWidth);
                int t = (int) (fRect.top*scaleHeight);
                int r = (int) (fRect.right*scaleWidth);
                int b = (int) (fRect.bottom*scaleHeight);

               // Log.e("TAG","[T"+i+"]:[left:"+l+",top:"+t+",right:"+r+",bottom:"+b+"]");
                //人脸检测坐标基于相机成像画面尺寸以及坐标原点。此处进行坐标转换以及原点(0,0)换算
                //人脸检测：坐标原点为相机成像画面的左上角，left、top、bottom、right以成像画面左上下右为基准
                //画面旋转后：原点位置不一样，根据相机成像画面的旋转角度需要换算到画布的左上角，left、top、bottom、right基准也与原先不一样，
                //如相对预览画面相机成像画面角度为90°那么成像画面坐标的top，在预览画面就为left。如果再翻转，那成像画面的top就为预览画面的right，且坐标起点为右，需要换算到左边
                /*if(isFront){
                    //此处前置摄像头成像画面相对于预览画面顺时针90°+翻转。left、top、bottom、right变为bottom、right、top、left，并且由于坐标原点由左上角变为右下角，X,Y方向都要进行坐标换算
                    canvas.drawRect(canvas.getWidth()-b,canvas.getHeight()-r,canvas.getWidth()-t,canvas.getHeight()-l,getPaint());
                }else{
                    //此处后置摄像头成像画面相对于预览画面顺时针270°，left、top、bottom、right变为bottom、left、top、right，并且由于坐标原点由左上角变为左下角，Y方向需要进行坐标换算

                }*/
                canvas.drawRect(canvas.getWidth()-b,l,canvas.getWidth()-t,r,getPaint());
            }
        }
        faceView.unlockCanvasAndPost(canvas);
    }

    //初始化画笔
    private Paint pb;
    private Paint getPaint(){
        if(pb == null){
            pb =new Paint();
            pb.setColor(Color.WHITE);
            pb.setStrokeWidth(10f);
            pb.setStyle(Paint.Style.STROKE);//使绘制的矩形中空
        }
        return pb;
    }

    //获取支持的最高人脸检测级别
    private int getFaceDetectMode(){
        if(faceDetectModes == null){
            return CaptureRequest.STATISTICS_FACE_DETECT_MODE_FULL;
        }else{
            return faceDetectModes[faceDetectModes.length-1];
        }
    }
}